package com.swak.frame.api.filter.spi;

import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.swak.frame.chain.FilterInvoker;
import com.swak.frame.common.SpringBeanFactory;
import com.swak.frame.context.BoundContext;
import com.swak.frame.dto.base.SysRestCode;
import com.swak.frame.exception.ApiExceptionUtil;
import com.swak.frame.extension.adapter.WhiteListAdapter;
import com.swak.frame.filter.ApiFilter;
import com.swak.frame.filter.FilterConstants;
import com.swak.frame.system.SystemConfigurable;

/**
 * 白名单校验 ClassName: WhiteListFilter.java
 * 
 * @author colley.ma
 * @date 2021年3月30日 下午3:45:55
 */
public class WhiteListFilter implements ApiFilter {
	private Logger logger = LoggerFactory.getLogger(this.getClass());

	private WhiteListAdapter whiteListAdapter = SpringBeanFactory.getBean(WhiteListAdapter.class);

	private SystemConfigurable systemConfig = SpringBeanFactory.getBean(SystemConfigurable.class);;

	@Override
	public void doFilter(BoundContext context, FilterInvoker<BoundContext> nextFilter) {
		if (systemConfig.getBoolean(FilterConstants.WHITE_LIST, true)) {
			logger.info("start doFilter:{}", DateTime.now().toString());
			String pin = context.getRequest().getPin();
			// 是否登录
			if (StringUtils.isEmpty(pin)) {
				return;
			}
			if (!whiteListAdapter.isWhiteList(context)) {
				ApiExceptionUtil.throwException(SysRestCode.INVALID_WHITE_LIST.getRetCode(),
						"白名单校验失败，您的【" + pin + "】不在白名单中，无访问【" + context.getAuthCode() + "】的权限~");
			}
		}
		// 下一个流程
		nextFilter.invoke(context);
	}
}
